﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Timers;
using Confcloud.Email.Templates;
using Smarly.Bussines.Model;
using Smarly.Core.Database;

namespace Smarly.Bussines.Email
{
	public class SubscriberSender
	{
		static readonly Timer EmailTimer = new Timer();

		private static readonly TimeSpan sendTime = new TimeSpan(8, 0, 0);
		private const string SubscribeDate = "SubscribeDate";
		public static void Start()
		{
			EmailTimer.Interval = GetTimerInterval();
			EmailTimer.AutoReset = false;
			EmailTimer.Elapsed += SendSubscribe;
			EmailTimer.Enabled = true;
		}

		private static void SendSubscribe(object sender, ElapsedEventArgs e)
		{
			EmailTimer.Enabled = false;

			DateTime now = DateTime.UtcNow;
			NewsModel t = BookTree.GetNews(now.Date.AddDays(-1).Add(sendTime), now.Date.Add(sendTime));

			try
			{
				if (t.Sections.Count > 0)
				{
					if (t.Subscribers != null)
					{
						foreach (var subscriber in t.Subscribers)
						{
							try
							{
								new SubscribeNewsEmail(subscriber, t).Post();
							}
							catch
							{
							}
						}
					}

				}

				SetSendDate(now);
			}
			catch
			{

			}
			EmailTimer.Interval = GetTimerInterval();
			EmailTimer.Enabled = true;
		}

		private static long GetTimerInterval()
		{
			DateTime lastSentDate = GetSendDate().SendDate;
			var now = DateTime.Now;

			long result = 1000;

			if (lastSentDate.Date.Add(sendTime).AddDays(1) >= now)
			{
				TimeSpan timer = lastSentDate.Date.Add(sendTime).AddDays(1) - now;
				result = timer.Ticks / 10000;
			}
			return result;
		}


		public static void SetSendDate(DateTime date)
		{
			SqlRepository.ExecuteProcedureReader("Smarly_Common_SetValue",
																									new List<SpParam>
				                                            {
					                                            new SpParam {Name = "@name", Value = SubscribeDate, Type = DbType.String},
					                                            new SpParam {Name = "@value", Value = date.ToString("R"), Type = DbType.String},
				                                            },
																									null,
																									(reader) =>
																									{
																										DateTime result = new DateTime();
																										while (reader.Read())
																										{
																											DateTime.TryParse(reader.GetStringOrNull("Value"), out result);
																										}
																										return new { SendDate = result };
																									});
		}

		public static dynamic GetSendDate()
		{
			return SqlRepository.ExecuteProcedureReader("Smarly_Common_GetValue",
																									new List<SpParam>
				                                            {
					                                            new SpParam {Name = "@name", Value = SubscribeDate, Type = DbType.String},
				                                            },
																									null,
																									(reader) =>
																									{
																										DateTime result = new DateTime();
																										while (reader.Read())
																										{
																											DateTime.TryParse(reader.GetStringOrNull("Value"), out result);
																										}
																										return new { SendDate = result };
																									});
		}
	}
}
